<template>
  <el-dialog :visible.sync="openDrawer" width="60%" :close-on-click-modal="false" @opened="opened">
    <el-collapse v-model="collapse" accordion>
      <el-collapse-item title="基本信息" name="1">
        <el-form :model="formData" label-width="150px">
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="渠道代码" required>
                <el-input v-model="formData.channelCode" placeholder="渠道代码" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="渠道名称" required>
                <el-input v-model="formData.channelName" placeholder="渠道中文名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="是否启用" required>
                <el-select v-model="formData.enable" style="width: 100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目的地国家" required>
                <el-select v-model="formData.country" filterable style="width: 100%;">
                  <el-option v-for="item in countrys" :key="item.code" :value="item.code" :label="item.nameCn" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="渠道类型" required>
                <el-select v-model="formData.channelType" placeholder="请选渠道类型" style="width: 100%;">
                  <el-option v-for="item in channelTypes" :key="item.value" :value="item.value" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运费科目" required>
                <el-select v-model="formData.baseChargeSubjectId" clearable filterable placeholder="如果没有可选项,请先新建费用科目" style="width: 100%;">
                  <el-option v-for="(item, index) in chargeSubjectOptions" :key="index" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="重量单位" label-position="top" required>
                <el-select v-model="formData.weightUnit" placeholder="重量单位" style="width:100%;">
                  <el-option value="KG" label="KG" />
                  <el-option value="POUNDS" label="POUNDS" />
                  <el-option value="OZ" label="OZ" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重量进位规则">
                <el-select v-model="formData.weightRoundingMode.right" style="width:100%;">
                  <el-option v-for="(option, index) in roundingMethodOptions" :key="index" :value="option.code" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="单箱最小重量(KG)">
                <el-input v-model="formData.cartonMinWeight" type="number" placeholder="单箱最小重量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- <el-form-item label="单箱最低费用" label-position="top">
                <el-input v-model="formData.minChargePerCarton" type="number" placeholder="单箱最低费用" />
              </el-form-item> -->
              <el-form-item label="燃油附加费方案">
                <el-select v-model="formData.fuelSurchargeId" filterable clearable placeholder="燃油附加费方案名称" style="width: 100%;">
                  <el-option v-for="item in fuelSurchargeOptions" :key="item.code" :value="item.code" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="燃油附加费科目" label-position="top">
                <el-select v-model="formData.fuelSurchargeChargeSubjectId" clearable filterable style="width:100%;" placeholder="如果没有可选项,请先新建费用科目">
                  <el-option v-for="(item, index) in chargeSubjectOptions" :key="index" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="偏远|超偏远邮编" label-position="top">
                <el-select v-model="formData.remoteZipcodeId" clearable filterable style="width:100%;" placeholder="如果没有可选项,请先新建费用科目">
                  <el-option v-for="(item) in remoteZipcodeOptions" :key="item.code" :value="item.code" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="佣金科目" label-position="top">
                <el-select v-model="formData.commissionChargeSubjectId" clearable filterable style="width:100%;" placeholder="如果没有可选项,请先新建费用科目">
                  <el-option v-for="(item, index) in chargeSubjectOptions" :key="index" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="佣金比率" label-position="top">
                <el-input v-model="formData.commission" type="number" placeholder="佣金比率" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="账单供应商名称" label-position="top" required>
                <el-select v-model="formData.invoiceSupplierId" placeholder="请选账单供应商" style="width:100%;">
                  <el-option v-for="(option, index) in invoiceSupplierOptions" :key="index" :value="option.id" :label="option.clientName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="整票最低费用">
                <el-input v-model="formData.minChargePerOrder" type="number" placeholder="整票最低费用" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="附加费方案">
                <el-select v-model="formData.surchargeId" filterable clearable placeholder="附加费方案名称" style="width: 100%;">
                  <el-option v-for="item in surchargeOptions" :key="item.value" :value="item.value" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否实时扣费" label-position="top" required>
                <el-select v-model="formData.realTimeTransaction" style="width:100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="用供应商成本做应收" label-position="top" required>
                <el-select v-model="formData.chargingBySupplierCost" style="width:100%;">
                  <el-option value="true" label="是" />
                  <el-option value="false" label="否" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="币种" label-position="top" required>
                <el-select v-model="formData.currency" style="width:100%;">
                  <el-option v-for="item in currencyOptions" :key="item.value" :value="item.value" :label="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="32">
            <el-col :span="12">
              <el-form-item label="计费重取值方式" required>
                <el-select v-model="formData.billedWeightCalculationMethodType" style="width: 100%;">
                  <el-option v-for="(option, index) in BilledWeightCalculationMethodTypes" :key="index" :value="option.code" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计费方式" required>
                <el-select v-model="formData.chargingByCarton" style="width: 100%;">
                  <el-option value="true" label="按件计费" />
                  <el-option value="false" label="按票计费" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.billedWeightCalculationMethodType && formData.billedWeightCalculationMethodType !='ACTUALLY_WEIGHT' && formData.billedWeightCalculationMethodType !='VOLUME'" :gutter="32">
            <el-col :span="12">
              <el-form-item label="体积重计算比率">
                <el-input v-model="formData.volumeWeightRadio" type="number" placeholder="体积重计算比率" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else-if="formData.billedWeightCalculationMethodType=='VOLUME'" :gutter="32">
            <el-col v-if="formData.chargingByCarton == 'false'" :span="12">
              <el-form-item label="整票最小体积(CBM)">
                <el-input v-model="formData.minTotalVolume" type="number" placeholder="整票最小体积" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.billedWeightCalculationMethodType && formData.billedWeightCalculationMethodType !='VOLUME' && formData.chargingByCarton == 'false' " :gutter="32">
            <el-col :span="12">
              <el-form-item label="整票最小计费重">
                <el-input v-model="formData.minTotalWeight" type="number" placeholder="整货最小重" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item v-show="formData.chargingBySupplierCost == 'false'" title="运费配置" name="2">
        <BasePriceNew v-show="addBasePrice" ref="basePriceNew" @basePriceOk="submit" />
        <BasePriceList v-show="!addBasePrice" ref="basePriceList" />
      </el-collapse-item>
      <el-collapse-item title="供应商渠道对接" name="3">
        <el-form :model="formData" label-position="right" label-width="100" style="margin: 0 25px;">
          <el-row :gutter="32">
            <el-col :span="8">
              <el-form-item label="供应商">
                <el-select v-model="formData.supplier" :label-in-value="true" placeholder="供应商" @change="supplierOptionChange">
                  <el-option v-for="item in supplierOptions" :key="item.supplier" :value="item.supplier" :label="item.supplier" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="API配置">
                <el-select v-model="formData.providerConfigId" placeholder="API配置" @change="providerConfigOptionChange">
                  <el-option v-for="item in providerConfigOptions" :key="item.id" :value="item.id" :label="item.shortName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商产品">
                <el-select v-model="formData.supplierChannelCode" placeholder="请选供应商产品">
                  <el-option v-for="(option, index) in supplierChannelCode" :key="index" :value="option.code" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="订单约束" name="4">
        <el-form :model="formData" label-position="right" label-width="100" style="margin: 0 25px;">
          <el-row :gutter="32">
            <el-col :span="24">
              <el-form-item label="订单约束">
                <el-select v-model="formData.limiters" multiple placeholder="请选订单约束" style="width: 100%;">
                  <el-option v-for="(option, index) in limiterOptions" :key="index" :value="option.id" :label="option.name" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <div slot="footer">
      <el-button style="margin-right: 8px" @click="openDrawer = false">取消</el-button>
      <el-button type="primary" @click="basePriceValidate">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import request from '@/utils/request'
import { copyProperty } from '@/utils/tools'
import { mapState } from 'vuex'
import BasePriceNew from './base_price_new'
import BasePriceList from './base_price_list'
export default {
  components: {
    BasePriceNew,
    BasePriceList
  },
  data() {
    return {
      addBasePrice: true,
      openDrawer: false,
      collapse: '1',
      productTypeOptions: [
        { 'value': 'SEA', 'name': '海运' },
        { 'value': 'AIR', 'name': '空运' },
        { 'value': 'GND', 'name': '陆运' }
      ],
      totalWeightRoundingMode: [
        { 'value': 'TWRM1', 'name': '每箱先进位后累加' },
        { 'value': 'TWRM2', 'name': '每箱累加后再进位' }
      ],
      channelTypes: [
        { 'value': 'UPS', 'name': 'UPS' },
        { 'value': 'FEDEX', 'name': 'FEDEX' },
        { 'value': 'USPS', 'name': 'USPS' },
        { 'value': 'DPD', 'name': 'DPD' },
        { 'value': 'TNT', 'name': 'TNT' },
        { 'value': 'SAGAWA', 'name': '佐川' },
        { 'value': 'DHL', 'name': 'DHL' },
        { 'value': 'TRUCK', 'name': 'TRUCK' }
      ],
      currencyOptions: [
        { 'value': 'USD', 'name': '美元' },
        { 'value': 'CNY', 'name': '人民币' },
        { 'value': 'EUR', 'name': '欧元' },
        { 'value': 'CAD', 'name': '加元' }
      ],
      formDataDefault: {
        enable: 'true',
        needPackage: 'false',
        channelCode: '',
        channelName: '',
        currency: 'USD',
        channelType: '',
        supplierChannelCode: '',
        providerId: '',
        providerConfigId: '',
        supplier: '',
        country: '',
        billedWeightCalculationMethodType: 'ACTUALLY_WEIGHT',
        weightUnit: 'KG',
        minChargePerOrder: 0,
        minChargePerCarton: 0,
        minTotalWeight: 0,
        cartonMinWeight: 0,
        volumeWeightRadio: 6000,
        commission: 0,
        chargingByCarton: 'true',
        realTimeTransaction: 'true', // 实时交易
        commissionChargeSubjectId: '',
        chargingBySupplierCost: 'false',
        invoiceSupplierId: '',
        roundingMode: '',
        limiters: [],
        effectiveFrom: '',
        zoneId: '',
        weightId: '',
        basePrice: [],
        baseChargeSubjectId: '',
        totalWeightRoundingMode: null,
        weightRoundingMode: {
          boundary: 0,
          left: 'RM1',
          right: 'RM1'
        },
        zoneDirection: '',
        surchargeId: '',
        fuelSurchargeId: '',
        fuelSurchargeChargeSubjectId: '',
        remoteZipcodeId: ''
      },
      formData: {
        enable: 'true',
        needPackage: 'false',
        channelCode: '',
        channelName: '',
        currency: 'USD',
        channelType: '',
        country: '',
        supplierChannelCode: '',
        providerId: '',
        providerConfigId: '',
        supplier: '',
        billedWeightCalculationMethodType: 'ACTUALLY_WEIGHT',
        weightUnit: 'KG',
        minChargePerOrder: 0,
        minChargePerCarton: 0,
        minTotalWeight: 0,
        cartonMinWeight: 0,
        volumeWeightRadio: 6000,
        commission: 0,
        chargingByCarton: 'false',
        realTimeTransaction: 'true', // 实时交易
        commissionChargeSubjectId: '',
        chargingBySupplierCost: 'false',
        invoiceSupplierId: '',
        roundingMode: '',
        limiters: [],
        effectiveFrom: '',
        zoneId: '',
        weightId: '',
        basePrice: [],
        baseChargeSubjectId: '',
        totalWeightRoundingMode: null,
        weightRoundingMode: {
          boundary: 0,
          left: 'RM1',
          right: 'RM1'
        },
        zoneDirection: '',
        surchargeId: '',
        fuelSurchargeId: '',
        fuelSurchargeChargeSubjectId: '',
        remoteZipcodeId: ''
      },
      BilledWeightCalculationMethodTypes: [
        { code: 'ACTUALLY_WEIGHT', name: '实重' },
        { code: 'NOT_BUBBLE', name: '实重和体积重取大者' }
      ],
      supplierOptions: [],
      supplierOptionMap: new Map(),
      providerConfigOptions: [],
      supplierChannelCode: [],
      chargeSubjectOptions: [],
      invoiceSupplierOptions: [],
      limiterOptions: [],
      roundingMethodOptions: [],
      fuelSurchargeOptions: [],
      remoteZipcodeOptions: []
    }
  },
  computed: {
    ...mapState(//
      {
        countrys: state => state.base.countrys,
        surchargeOptions: state => state.base.surchargeOptions
      }
    )
  },
  created() {
    this.loadSupplierOptions()
    this.loadChargeSubjectOptions()
    this.loadLimiterOptions()
    if (this.countrys.length === 0) {
      this.$store.dispatch('getCountrys')
    }
    if (this.surchargeOptions.length === 0) {
      this.$store.dispatch('getSurchargOptions')
    }
    this.loadRoundingMethodOptions()
    this.loadInvoiceSupplierOptions()
    this.loadFuelSurchargeOptions()
    this.loadRemoteZipcodeOptions()
  },
  mounted() {
  },
  methods: {
    loadFuelSurchargeOptions() {
      request({
        url: 'fuel/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.fuelSurchargeOptions = res.data
          }
        }
      })
    },
    loadRemoteZipcodeOptions() {
      request({
        url: 'remote/zipcode/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.remoteZipcodeOptions = res.data
          }
        }
      })
    },
    loadRoundingMethodOptions() {
      request({
        url: 'channel/rounding-method',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.roundingMethodOptions = res.data
          }
        }
      })
    },
    supplierOptionChange(value) {
      if (!value) {
        return
      }
      const supplierOptionChange = value.label || value
      this.providerConfigOptions = this.supplierOptionMap.get(supplierOptionChange).configOptions
      this.formData.providerId = this.supplierOptionMap.get(supplierOptionChange).providerId
      if (!value.fromEdit) {
        this.formData.supplierChannelCode = ''
        this.formData.providerConfigId = ''
      }

      if (this.providerConfigOptions.length === 1) {
        this.formData.providerConfigId = this.providerConfigOptions[0].id
        this.providerConfigOptionChange({ value: this.formData.providerConfigId })
      }
    },
    providerConfigOptionChange(value) {
      if (!value) {
        return
      }
      this.loadSupplierChannelOptions()
    },
    loadSupplierOptions() {
      request({
        url: 'channel-provider/supplier-option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.supplierOptions = res.data
            res.data.forEach(ele => {
              this.supplierOptionMap.set(ele.supplier, ele)
            })
          }
        }
      })
    },
    loadSupplierChannelOptions() {
      request({
        url: 'channel-provider/channel-option?providerId=' + this.formData.providerId + '&providerConfigId=' + this.formData.providerConfigId,
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.supplierChannelCode = res.data
          } else {
            this.supplierChannelCode = []
            this.formData.supplierChannelCode = ''
          }
        }
      })
    },
    loadChargeSubjectOptions() {
      request({
        url: 'charge-subject/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.chargeSubjectOptions = res.data
          }
        }
      })
    },
    loadInvoiceSupplierOptions() {
      request({
        url: 'supplier/get',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.invoiceSupplierOptions = res.data
          }
        }
      })
    },
    loadLimiterOptions() {
      request({
        url: 'product/limiter/option',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.limiterOptions = res.data
          }
        }
      })
    },
    basePriceValidate() {
      if (this.addBasePrice && (this.formData.chargingBySupplierCost === 'false' || !this.formData.chargingBySupplierCost)) {
        this.$refs.basePriceNew.doValidate()
      } else {
        this.submit()
      }
    },
    submit(data) {
      if (data) {
        copyProperty(this.formData, data)
      }

      request({
        url: 'product/price/base/add',
        method: 'post',
        data: this.formData
      }).then(res => {
        if (res.success) {
          this.openDrawer = false
          this.$emit('query')
          this.$store.dispatch('getChannelOptions')
        }
      })
    },
    edit(row) {
      copyProperty(this.formData, this.formDataDefault)
      this.addBasePrice = false
      this.formData.id = row.id
      copyProperty(this.formData, row)
      if (row.supplier) {
        this.supplierOptionChange({ label: row.supplier, fromEdit: true })
        this.loadSupplierChannelOptions()
      } else {
        this.formData.providerId = ''
        this.formData.supplierChannelCode = ''
        this.formData.providerConfigId = ''
      }
      this.collapse = '2'
      this.openDrawer = true
    },
    copy(row) {
      copyProperty(this.formData, this.formDataDefault)
      copyProperty(this.formData, row)
      Reflect.deleteProperty(this.formData, 'id')
      this.addBasePrice = true
      if (row.supplier) {
        this.supplierOptionChange({ label: row.supplier, fromEdit: true })
        this.loadSupplierChannelOptions()
      } else {
        this.formData.providerId = ''
        this.formData.supplierChannelCode = ''
        this.formData.providerConfigId = ''
      }
      this.collapse = '2'
      this.openDrawer = true
      this.$refs.basePriceNew.clean()
    },
    add() {
      Reflect.deleteProperty(this.formData, 'id')
      copyProperty(this.formData, this.formDataDefault)
      this.collapse = '1'
      this.openDrawer = true
      this.addBasePrice = true
    },
    opened() {
      if (this.addBasePrice) {
        this.$refs.basePriceNew.clean()
      } else {
        this.$refs.basePriceList.queryData.channelId = this.formData.id
        this.$refs.basePriceList.list()
      }
    }
  }
}
</script>
